﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading;
using System.Reflection;

namespace Kocic.RepositoryManagement.SystemFile
{
    /// <summary>
    /// Allows entity manager objects to re-use a single instance of an object context for the ADO.NET Entity Framework.
    /// </summary>
    /// <typeparam name="TContext">The type of the entity object context to use within the execution context of this instance.</typeparam>
    public class SystemFileExecutionContext<TContext> : DataSourceExecutionContext<TContext>
        where TContext : FileContext, new()
    {
        /// <summary>
        /// Creates an instance of the EntityExecutionContext class.
        /// </summary>
        public SystemFileExecutionContext()
        {

        }

        /// <summary>
        /// Creates an instance of the EntityExecutionContext class.
        /// </summary>
        public SystemFileExecutionContext(String fileName)
            : base(fileName)
        {

        }


        /// <summary>
        /// Initializes the system file data context by utilizing reflection to pass in the file name to the constructor of the instance of TContext.
        /// </summary>
        protected override void InitializeDataSource()
        {
            //Gets the type of the generic context defined. Uses reflection to invoke the parameterized constructor to pass in the connection string needed to connect to CRM.
            Type t = typeof(TContext);
            ConstructorInfo contextConstructor = t.GetConstructor(new Type[] { typeof(string) });
            object contextClassObject = contextConstructor.Invoke(new object[] { this.DataString });

            this.DataSource = contextClassObject as TContext;

            ExecutionContext = this;
            this.Disposed = false;
        }

        /// <summary>
        /// Disposes unmanaged resources.
        /// </summary>
        /// <param name="disposing">Value indicating if to invoke the method from the IDisposable.Dispose implementation or from the finalizer.</param>
        protected override void Dispose(Boolean disposing)
        {
            if (disposing)
            {
                if (this.Disposed)
                {
                    return;
                }

                ExecutionContext = null;

                this.DataSource.Dispose();

                base.Dispose(disposing);
            }
        }
    }
}